import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_test/test1.dart';

main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      home: MyHome(),
    );
  }
}

class MyHome extends StatefulWidget {
  const MyHome({Key? key}) : super(key: key);

  @override
  _MyHomeState createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {
  List<List<Offset>> _list = [];

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Listener(
        onPointerDown: (PointerDownEvent event) {
          setState(() {
            _list.add([event.localPosition]);
          });
        },
        onPointerMove: (PointerMoveEvent event) {
          setState(() {
            _list[_list.length - 1].add(event.localPosition);
          });
        },
        onPointerUp: (PointerUpEvent event) {
          setState(() {
            _list[_list.length - 1].add(event.localPosition);
          });
          _list.remove(_list.length - 1);
        },
        onPointerCancel: (PointerCancelEvent event) {
          setState(() {
            _list[_list.length - 1].add(event.localPosition);
          });
          _list.remove(_list.length - 1);
        },
        child: CustomPaint(
          painter: MyPaint(_list),
          child: Container(
            width: double.infinity,
            height: double.infinity,
          ),
        ),
      ),
    );
  }
}

class MyPaint extends CustomPainter {
  List<List<Offset>> _list ;

  MyPaint(this._list);

  Paint _paint = Paint()
    ..color = Colors.lightBlueAccent
    ..style = PaintingStyle.stroke
    ..strokeWidth = 3.0;

  @override
  void paint(Canvas canvas, Size size) {
    // var iterator=_list.iterator;
    // while( iterator.moveNext()){
    //   var element1=iterator.current;
    //
    // }
    _list.removeWhere((element1){
      Path path = Path();
      for (int i = 0; i < element1.length; i++) {
        if (i == 0) {
          path.moveTo(element1[i].dx, element1[i].dy);
        } else {
          path.lineTo(element1[i].dx, element1[i].dy);
        }
      }
      canvas.drawPath(path, _paint);
      pri(_list.length);
      // _list.remove(element1);
      return false;
    });

  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
